package utils;

import java.io.UnsupportedEncodingException;

/**
 * Created with IntelliJ IDEA.
 * User: zhangyong
 * Date: 13-9-1
 * Time: 上午9:22
 * To change this template use File | Settings | File Templates.
 */
public class ByteUtils {

    public static final String DEFAULT_CHARSET_NAME = "utf-8";

    public static final byte[] getBytes(String k) {
        if (k == null || k.length() == 0) {
            throw new IllegalArgumentException("Key must not be blank");
        }
        try {
            return k.getBytes(DEFAULT_CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    final static int[] sizeTable = {
            9,
            99,
            999,
            9999,
            99999,
            999999,
            9999999,
            99999999,
            999999999,
            Integer.MAX_VALUE
    };

    public static final int stringSize(int x) {
        for (int i = 0; ; i++) {
            if (x <= sizeTable[i]) {
                return i + 1;
            }
        }
    }

    public static final int setArguments(byte[] bb, int index, Object... args) {
        boolean wasFirst = true;
        int s = index;
        for (Object o : args) {
            if (wasFirst) {
                wasFirst = false;
            } else {
                bb[s++] = Constants.SPACE;
            }
            if (o instanceof byte[]) {
                byte[] tmp = (byte[]) o;
                //拷贝 从数据的index是0 开始拷贝拷贝到 最终的数据 并且锁定tmp的大小 调用的是系统的 字节 arraycopy方法
                System.arraycopy(tmp, 0, bb, s, tmp.length);
                s += tmp.length;
            } else if (o instanceof Integer) {
                int v = ((Integer) o).intValue();
                s += stringSize(v);
                getBytes(v, s, bb);
            } else if (o instanceof String) {
                byte[] tmp = getBytes((String) o);
                System.arraycopy(tmp, 0, bb, s, tmp.length);
                s += tmp.length;
            } else if (o instanceof Long) {
                long v = ((Long) o).longValue();
                s += stringSize(v);
                getBytes(v, s, bb);
            }

        }
        System.arraycopy(Constants.CRLF, 0, bb, s, 2);
        s += 2;
        return s;
    }






}
